<?php

class Vega_Db_Rowset implements Iterator, Countable
{

    /**
     * Database object
     *
     * @var Vega_Db_Abstract
     */
    protected $_db = null;

    /**
     * The query result
     *
     * @var resource | object
     */
    protected $_result = null;

    /**
     * Result count
     *
     * @var integer
     */
    protected $_count = 0;

    /**
     * Current row data
     *
     * @var mixed array
     */
    protected $_currentRow = null;

    /**
     * Key number of the current row
     * @var
     */
    protected $_currentRowKey = 0;

    /**
     * Constructor
     *
     * @param Vega_Db_Abstract $db
     * @param mixed $result
     */
    public function __construct(Vega_Db_Abstract $db, $result)
    {
        $this->_db     = $db;
        $this->_result = $result;
        $this->_count  = $this->_db->numRows($this->_result);
    }

 

    /**
     * Rewind
     */
    public function rewind()
    {
        $this->_currentRowKey = 0;
        $this->_currentRow    = null;
    }

    /**
     * Returns the current row
     * 
     * @return array
     */
    public function current()
    {
        if (null === $this->_currentRow)
        {
            $this->next();
        }
        return $this->_currentRow;
    }

    /**
     * Returns the key of the current row
     *
     * @return integer
     */
    public function key()
    {
        return $this->_currentRowKey;
    }

    /**
     * Forward to next row
     *
     * @return array
     */
    public function next()
    {
        $this->_currentRowKey++;
        $this->_currentRow = $this->_db->fetchRow($this->_result);
        return $this->_currentRow;
    }

    /**
     * Valid?
     *
     * @return boolean
     */
    public function valid()
    {
        if ($this->_currentRowKey > $this->_count)
        {
            return false;
        }
        return true;
    }

    /**
     * Implements Countable interface
     */
    public function count()
    {
       return $this->_count;
    }
}
